package lab.bmp.artist;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.EntityContext;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import lab.bmp.NamedRecordBean;
import lab.bmp.track.TrackPK;
import lab.logging.LoggingUtil;
import ru.ssau.DatabaseHelper;

/**
 *
 * @author Smike
 */
public class ArtistBean implements NamedRecordBean<ArtistPK> {

    EntityContext context;
    DataSource datasource;
    lab.domain.Artist artist;
    boolean changed;

    public void setEntityContext(EntityContext ctx) throws EJBException, RemoteException {
        this.context = ctx;
    }

    public void unsetEntityContext() throws EJBException, RemoteException {
        this.context = null;
    }

    public void ejbRemove() throws RemoveException, EJBException, RemoteException {
        ArtistPK key = getCurrentKey();
        lab.domain.Artist artist = new lab.domain.Artist();
        artist.setId(key.getId());
        Connection connection = getConnection();
        try {
            DatabaseHelper.deleteArtist(connection, artist);
        } catch (SQLException ex) {
            throw new RemoveException(ex.getMessage());
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
                // do nothing
            }
        }
    }

    public void ejbActivate() throws EJBException, RemoteException {
        // do nothing
    }

    public void ejbPassivate() throws EJBException, RemoteException {
    }

    public void ejbLoad() throws EJBException, RemoteException {
        changed = false;
        // lazy
    }

    private void initializeIfNeeded() {
        if (artist == null) {
            ArtistPK key = getCurrentKey();
            Connection connection = getConnection();
            try {
                this.artist = DatabaseHelper.findArtist(connection, key.getId());
            } catch (SQLException ex) {
                throw new RuntimeException(ex.getMessage());
            } finally {
                try {
                    if (connection != null) {
                        connection.close();
                    }
                } catch (Exception e) {
                    // do nothing
                }
            }
        }
    }

    public void ejbStore() throws EJBException, RemoteException {
        if (artist != null && changed) {
            Connection connection = getConnection();
            try {
                DatabaseHelper.updateArtist(connection, artist);
                LoggingUtil.log(LoggingUtil.ARTIST);
            } catch (SQLException ex) {
                throw new RuntimeException(ex.getMessage());
            } finally {
                try {
                    if (connection != null) {
                        connection.close();
                    }
                } catch (Exception e) {
                    // do nothing
                }
            }
        }
    }

    ArtistPK getCurrentKey() {
        return (ArtistPK) context.getPrimaryKey();
    }

    public String getName() {
        initializeIfNeeded();
        return artist.getName();
    }

    public void setName(String name) {
        initializeIfNeeded();
        changed = true;
        artist.setName(name);
    }

    public Integer getId() {
        return getCurrentKey().getId();
    }

    public void setId(Integer id) {
        initializeIfNeeded();
        changed = true;
        artist.setId(id);
    }

    public ArtistPK ejbCreate(Integer id, String name) throws CreateException {
        lab.domain.Artist artist = new lab.domain.Artist();
        artist.setName(name);
        try {
            return new ArtistPK(DatabaseHelper.insertArtist(getConnection(), artist));
        } catch (SQLException ex) {
            throw new CreateException(ex.getMessage());
        }
    }

    public ArtistPK ejbFindByPrimaryKey(ArtistPK key) throws FinderException {
        lab.domain.Artist artist;
        try {
            artist = DatabaseHelper.findArtist(getConnection(), key.getId());
        } catch (SQLException ex) {
            throw new FinderException(ex.getMessage());
        }
        return key;
    }

    public Collection ejbFindAll() throws FinderException {
        try {
            Collection<lab.domain.Artist> artists = DatabaseHelper.findArtists(getConnection());
            Collection<ArtistPK> keys = new ArrayList<ArtistPK>();
            for (lab.domain.Artist artist : artists) {
                keys.add(new ArtistPK(artist.getId()));
            }
            return keys;
        } catch (SQLException ex) {
            throw new FinderException(ex.getMessage());
        }
    }

    public Collection ejbFindByTrack(TrackPK key) throws FinderException {
        try {
            Collection<lab.domain.Artist> artists = DatabaseHelper.findTrackArtists(getConnection(), key.getId());
            Collection<ArtistPK> keys = new ArrayList<ArtistPK>();
            for (lab.domain.Artist g : artists) {
                keys.add(new ArtistPK(g.getId()));
            }
            return keys;
        } catch (SQLException ex) {
            throw new FinderException(ex.getMessage());
        }
    }

    Connection getConnection() {
        try {
            return getDataSource().getConnection();
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }

    DataSource getDataSource() {
        if (datasource == null) {
            try {
                datasource = (DataSource) new InitialContext().lookup("oracleDS");
                return datasource;
            } catch (NamingException ex) {
                throw new RuntimeException(ex);
            }
        }
        return datasource;
    }
}
